package com.snmp.smn.agent;

import java.net.Socket;

import com.snmp.smn.pdu.PDUFactory;
import com.snmp.smn.utils.Utilities;

public class MessageProcessor extends Thread {

	private Socket socket;

	public MessageProcessor(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		try {
			byte[] b = new byte[1024];
			socket.getInputStream().read(b);
			String message = new String(b).trim();
			
			Utilities.log("Processing message : " + message);
			
			if(message.length() > 2 && Utilities.isCorrectVersion(message)) {
				if (Utilities.isGetRequest(message)) {
					if (Utilities.isHeartBeat(message)) {
						sendHeartBeat();
					}
				} else if (Utilities.isSetRequest(message)) {
					executeCommand(Utilities.getMessageData(message));
				}
			}
			
			Utilities.log("Processed message : " + message);
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void executeCommand(String command) throws Exception {
		Utilities.log("Executing command : " + command);
		
		Process p = Runtime.getRuntime().exec(command);
		p.waitFor();
		
		Utilities.log("Successfully executed command : " + command);
	}

	private void sendHeartBeat() throws Exception {
		Utilities.log("Sending heartbeat...");
		
		byte[] b = PDUFactory.createHeartBeatResponsePDU();
		socket.getOutputStream().write(b);
	}
}
